#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 文件名称: medical_consult.py
# 文件保存路径: backend/models/medical_consult.py
"""
医患咨询数据模型
为微信小程序医生交流功能提供数据支持
"""

from backend.infrastructure.database import db
from datetime import datetime


class MedicalConsult(db.Model):
    """医患咨询记录模型"""
    __tablename__ = 'medical_consults'
    
    id = db.Column(db.Integer, primary_key=True, comment='咨询ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    student_id = db.Column(db.Integer, db.ForeignKey('students.id'), nullable=True, comment='学生ID')
    
    # 咨询基本信息
    title = db.Column(db.String(200), nullable=False, comment='咨询标题')
    content = db.Column(db.Text, nullable=False, comment='咨询内容')
    category = db.Column(db.String(50), nullable=False, comment='咨询分类')
    priority = db.Column(db.String(20), default='normal', comment='优先级')
    status = db.Column(db.String(20), default='pending', comment='状态')
    images = db.Column(db.JSON, nullable=True, comment='相关图片')
    
    # 医生回复信息
    doctor_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, comment='医生ID')
    doctor_name = db.Column(db.String(100), nullable=True, comment='医生姓名')
    doctor_title = db.Column(db.String(100), nullable=True, comment='医生职称')
    reply_content = db.Column(db.Text, nullable=True, comment='回复内容')
    reply_images = db.Column(db.JSON, nullable=True, comment='回复图片')
    replied_at = db.Column(db.DateTime, nullable=True, comment='回复时间')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    user = db.relationship('User', foreign_keys=[user_id], backref='medical_consults')
    student = db.relationship('Student', backref='medical_consults')
    doctor = db.relationship('User', foreign_keys=[doctor_id])
    
    def __repr__(self):
        return f'<MedicalConsult {self.id}: {self.title}>'
    
    def to_dict(self):
        """转换为字典格式"""
        try:
            return {
                'id': self.id,
                'user_id': self.user_id,
                'student_id': self.student_id,
                'title': self.title,
                'content': self.content,
                'category': self.category,
                'priority': self.priority,
                'status': self.status,
                'images': self.images or [],
                'doctor_id': self.doctor_id,
                'doctor_name': self.doctor_name,
                'doctor_title': self.doctor_title,
                'reply_content': self.reply_content,
                'reply_images': self.reply_images or [],
                'replied_at': self.replied_at.isoformat() if self.replied_at else None,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None
            }
        except Exception as e:
            # 如果序列化失败，返回基本信息
            return {
                'id': self.id,
                'title': self.title,
                'content': self.content,
                'category': self.category,
                'priority': self.priority,
                'status': self.status,
                'error': f'Serialization error: {str(e)}'
            }
    
    @classmethod
    def get_by_user(cls, user_id, status=None, page=1, per_page=10):
        """根据用户ID获取咨询记录"""
        query = cls.query.filter(cls.user_id == user_id)
        
        if status:
            query = query.filter(cls.status == status)
        
        return query.order_by(cls.created_at.desc()).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
    
    @classmethod
    def get_pending_count(cls):
        """获取待回复咨询数量"""
        return cls.query.filter(cls.status == 'pending').count()
    
    @classmethod
    def get_by_doctor(cls, doctor_id, page=1, per_page=10):
        """根据医生ID获取咨询记录"""
        return cls.query.filter(cls.doctor_id == doctor_id).order_by(
            cls.created_at.desc()
        ).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
    
    def add_reply(self, doctor_id, doctor_name, doctor_title, reply_content, reply_images=None):
        """添加医生回复"""
        self.doctor_id = doctor_id
        self.doctor_name = doctor_name
        self.doctor_title = doctor_title
        self.reply_content = reply_content
        self.reply_images = reply_images or []
        self.replied_at = datetime.utcnow()
        self.status = 'replied'
        self.updated_at = datetime.utcnow()
    
    def close_consult(self):
        """关闭咨询"""
        self.status = 'closed'
        self.updated_at = datetime.utcnow()


class ConsultAttachment(db.Model):
    """咨询附件模型"""
    __tablename__ = 'consult_attachments'
    
    id = db.Column(db.Integer, primary_key=True, comment='附件ID')
    consult_id = db.Column(db.Integer, db.ForeignKey('medical_consults.id'), nullable=False, comment='咨询ID')
    file_type = db.Column(db.String(20), nullable=False, comment='文件类型')  # image, document
    file_name = db.Column(db.String(255), nullable=False, comment='文件名')
    file_path = db.Column(db.String(500), nullable=False, comment='文件路径')
    file_size = db.Column(db.Integer, nullable=True, comment='文件大小')
    uploaded_by = db.Column(db.String(20), nullable=False, comment='上传者类型')  # user, doctor
    
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    
    # 关联关系
    consult = db.relationship('MedicalConsult', backref='attachments')
    
    def __repr__(self):
        return f'<ConsultAttachment {self.id}: {self.file_name}>'
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'consult_id': self.consult_id,
            'file_type': self.file_type,
            'file_name': self.file_name,
            'file_path': self.file_path,
            'file_size': self.file_size,
            'uploaded_by': self.uploaded_by,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


class ConsultCategory(db.Model):
    """咨询分类模型"""
    __tablename__ = 'consult_categories'
    
    id = db.Column(db.Integer, primary_key=True, comment='分类ID')
    code = db.Column(db.String(50), unique=True, nullable=False, comment='分类代码')
    name = db.Column(db.String(100), nullable=False, comment='分类名称')
    description = db.Column(db.Text, nullable=True, comment='分类描述')
    sort_order = db.Column(db.Integer, default=0, comment='排序')
    is_active = db.Column(db.Boolean, default=True, comment='是否启用')
    
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    def __repr__(self):
        return f'<ConsultCategory {self.code}: {self.name}>'
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'code': self.code,
            'name': self.name,
            'description': self.description,
            'sort_order': self.sort_order,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    @classmethod
    def get_active_categories(cls):
        """获取启用的分类"""
        return cls.query.filter(cls.is_active == True).order_by(cls.sort_order).all()
